﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SCCL2010
{
    public static class Fields
    {
        /// <summary>
        /// Gets the InternalName of the field for the supplied SPList.
        /// </summary>
        /// <param name="list"></param>
        /// <param name="cFieldDisplayName"></param>
        /// <returns>returns a string value representing the InternalName of the field.</returns>
        public static string GetInternalName(SPList list, string cFieldDisplayName)
        {
            try
            {
                foreach (SPField fld in list.Fields)
                {
                    if (fld.Title == cFieldDisplayName)
                        return fld.InternalName;
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(list.ParentWeb, "Fields.GetInternalName", ex);
            }
            return "";
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="workList"></param>
        /// <param name="cFieldName"></param>
        /// <param name="cChoiceValue"></param>
        /// <returns></returns>
        public static bool HasChoiceValue(SPList workList, string cFieldName, string cChoiceValue)
        {
            try
            {
                SPFieldChoice oChoiceField = (SPFieldChoice)workList.Fields[cFieldName];

                foreach (string choice in oChoiceField.Choices)
                {
                    if (choice == cChoiceValue)
                        return true;
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(workList.ParentWeb, "Fields.HasChoiceValue", ex);
            }
            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workList"></param>
        /// <param name="cFieldName"></param>
        /// <param name="cChoiceValue"></param>
        public static void AddChoiceValue(SPList workList, string cFieldName, string cChoiceValue)
        {
            try
            {
                SPFieldChoice oChoiceField = (SPFieldChoice)workList.Fields[cFieldName];
                oChoiceField.Choices.Add(cChoiceValue);
                oChoiceField.Update();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(workList.ParentWeb, "Fields.AddChoiceValue", ex);
            }
        }
    }
}
